<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
	<style>
		#ul1 {
			width: 400px;
			height: 300px;
			border: 1px solid #000;
			overflow: auto;
		}

		li.me {
			color: green;
		}
		#error {
			color: red;
			text-align: center;
			height: 20px;
			line-height: 20px;
		}
	</style>
	<script src="http://localhost:8080/socket.io/socket.io.js"></script>
	<script>


		window.onload = function() {
			let oTxt = document.querySelector('#txt1');
			let oBtn = document.querySelector('#btn1');
			let oUl = document.querySelector('#ul1');

			let sock = io.connect('ws://localhost:8080/');

			// 不论何时，只要连接到服务器就会触发这里一次
			sock.on('connect', function () {
				console.log('已连接');
				document.querySelector('#error').style.display = 'none';
			});
			// 只要断开服务器，这里就会触发一次。
			sock.on('disconnect', function() {
				console.log('已断开')
				document.querySelector('#error').style.display = 'block';
			})

			oBtn.onclick = function() {
				sock.emit('msg', oTxt.value);
				let oLi = document.createElement('li');
				oLi.innerHTML = oTxt.value;
				oTxt.value = '';
				oLi.classList.add('me');
				oUl.appendChild(oLi);
			}

			sock.on('msg', str => {
				let oLi = document.createElement('li');
				oLi.innerHTML = str;
				oUl.appendChild(oLi);
			});
		}
	</script>
</head>
<body>
	<div id="error">无法连接到服务器，请检查网络</div>
	<ul id="ul1">

	</ul>
	<textarea id="txt1" cols="60" rows="5"></textarea>
	<input type="button" value="发送" id="btn1">
</body>
</html>